<?PHP
$saveName = isset ($_POST['saveName']) ? $_POST['saveName'] : "new.jpg";
foreach ($_FILES as $fieldName => $file) {
	move_uploaded_file($file['tmp_name'], "./images/" . $file['name']);
	$sample = "./images/" . $file['name'];
	$target = "./images/" . $saveName;
	$target2 = "./images/thumb/" . $saveName;
	$old_mask = umask(0);
	chmod($sample, 0777);
	$width_max = 0;
	$height_max = 0;
	$width_thumb = 0;
	$heigh_thumb = 0;
	$tx = GetImageSize($sample);
	if ($tx[0] < 600 && $tx[1] < 550) {
		$width_max = $tx[0];
		$height_max = $tx[1];
	} else {
		$MIN_SCALE = (600 / $tx[0]) < (550 / $tx[1]) ? (600 / $tx[0]) : (550 / $tx[1]);

		$width_max = intval($tx[0] * $MIN_SCALE);
		$height_max = intval($tx[1] * $MIN_SCALE);
	}
	makethumb2($sample, $target, $width_max, $height_max);
	if (isset ($_POST['width_min']) && isset ($_POST['height_min'])) {
		if ($tx[0] < $_POST['width_min']) {
			$width_thumb = $tx[0];
			$height_thumb = $tx[1];
		} else {
			$MIN_SCALE = $_POST['width_min'] / $tx[0];
			$width_thumb = intval($tx[0] * $MIN_SCALE);
			$height_thumb = intval($tx[1] * $MIN_SCALE);
		}
		makethumb2($sample, $target2, $width_thumb, $height_thumb);
	}
	chmod($target2, 0777);
	chmod($target, 0777);
	umask($old_mask);
	unlink($sample);
	echo "http://" . $_SERVER['HTTP_HOST'] . "/solarsense/amfphp/services/images/thumb/" . $saveName;
	//echo "http://" . $_SERVER['HTTP_HOST'] . "/CMS/amfphp/services/images/thumb/" . $saveName;
}
function makethumb2($srcFile, $dstFile, $dstW, $dstH) {
	$data = GetImageSize($srcFile, & $info);
	switch ($data[2]) {
		case 1 :
			$im = @ ImageCreateFromGIF($srcFile);
			break;
		case 2 :
			$im = @ ImageCreateFromJPEG($srcFile);
			break;
		case 3 :
			$im = @ ImageCreateFromPNG($srcFile);
			break;
	}
	$srcW = ImageSX($im);
	$srcH = ImageSY($im);
	$red = imagecolorallocate($im, 255, 255, 255);
	imagefill($im, 0, 0, $red);
	$ni = ImageCreateTrueColor($dstW, $dstH);
	imagecopyresampled($ni, $im, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
	ImageJpeg($ni, $dstFile, 100);
	imagedestroy($im);
	imagedestroy($ni);
}
exit;
?>
